﻿#系统类包
import os
import uuid
from util import download
from util import log
import SimpleITK as sitk
import json
import numpy as np


class Nii2Mask(object):
    def __init__(self):
        self.endpath = os.getcwd()
        self.download_handl = download.Download()
        self.log = log.lgtest()
        self.log_name = 'Nii2Mask'
    def process(self,data):
        try:
            request_uuid = str(uuid.uuid4())
            self.log.lognow(request_uuid + '-----> Nii2Mask.process request: ' + str(data), 'info', self.log_name)
            niiMap = data['niiMap']
            resultPath = data['resultPath']

            tmpFilePath = os.path.join(resultPath, "tmp")
            os.makedirs(tmpFilePath, exist_ok=True)
            for key in niiMap:
                niiUrl = niiMap[key]
                # 下载
                niiFilePath = os.path.join(tmpFilePath, key + ".nii.gz")
                try:
                    self.download_handl.download_remote_local(niiUrl, niiFilePath)
                except Exception as ex:
                    self.log.lognow('Nii2Mask download mask fail! [index = ' + key + '] err: ' + str(ex), 'error', self.log_name)
                    return {"msg": "Nii2Mask download mask fail! [index = " + key + ']', "data": {}, "code": 1}

            for key in niiMap:
                try:
                    item_arr = []
                    niiFilePath = os.path.join(tmpFilePath, key +  ".nii.gz")
                    img = sitk.ReadImage(niiFilePath)
                    np_image = sitk.GetArrayFromImage(img)
                    rows, columns = np_image.shape[-2:]
                    layers = np_image.shape[0]
                    for i in range(layers):
                        item = {}
                        result_list = []
                        slice_data = np_image[i, :, :]
                        for val in np.flatnonzero(slice_data):
                            if val != 0:
                                result_list.append(int(val))
                        # for col in range(slice_data.shape[0]):
                        #     for row in range(slice_data.shape[1]):
                        #         if slice_data[col, row] != 0:
                        #             value = row * columns + col
                        #             result_list.append(value)
                        if len(result_list) > 0:
                            item['layer'] = i
                            item['result'] = json.dumps(result_list)
                            item_arr.append(item)
                    result_file_path = os.path.join(resultPath, key)
                    with open(result_file_path, 'w') as file:
                        json.dump(item_arr, file)
                except Exception as ex:
                    self.log.lognow('Nii2Mask convert fail! [index = ' + key + '] err: ' + str(ex), 'error', self.log_name)
                    return {"msg": "Nii2Mask convert fail! [index = " + key + ']', "data": {}, "code": 1}

            self.log.lognow(request_uuid + '-----> Nii2Mask.process response: success', 'info', self.log_name)

            return {"msg": "", "data": {}, "code": 0}
        except Exception as e:
            self.log.lognow('Nii2Mask fail ' + str(e), 'error', self.log_name)
            return {"msg": "Nii2Mask fail", "data": {}, "code": 1}





        
        
